const {app, BrowserWindow, Menu, globalShortcut} = require('electron');
const process = require('process');
const pugStuff = require('electron-pug');
const path = require('path');

require('electron-reload')(__dirname, {
	electron: path.join(__dirname, 'node_modules', '.bin', 'electron')
});

let win;
let pageVariables = {
	title: '登录'
};
global.pageVariables = pageVariables;
global.parcel = {
	onClose: function () {
	}
};

async function init() {
	win = new BrowserWindow({
		width: 1024,
		height: 768,
		webPreferences: {
			nodeIntegration: true
		}
	});
	Menu.setApplicationMenu(null);
	globalShortcut.register('CmdOrCtrl+Alt+Shift+Z', function () {
		win.webContents.openDevTools();
	});
	globalShortcut.register('CmdOrCtrl+Shift+Delete', function () {
		win.loadURL(`file://${__dirname}/main.pug`);
	});
	globalShortcut.register('CmdOrCtrl+Alt+Shift+Q', function () {
		win.loadFile('fatal.html');
	});
	win.on('close', () => {
		global.parcel.onClose();
	});
	try {
		let pug = await pugStuff({}, pageVariables);
		pug.on('error', function (err) {
			console.error(err);
			win.loadFile('fatal.html');
		});
	} catch (e) {
		// should not reach here, terribly wrong
		await win.loadFile('fatal.html');
	}
	await win.loadURL(`file://${__dirname}/main.pug`);
}

function cleanUp() {
	if (process.platform !== 'darwin') {
		app.quit();
	}
}

app.on('ready', init);
app.on('window-all-closed', cleanUp);
app.on('active', async function () {
	if (win == null) {
		await init();
	}
});
